import { Form } from "@arco-design/web-react";
import type { KeyboardEvent } from "react";
import { ModalBody, ModalContent, ModalFooter } from "../content";
import { useModalRef } from "../hook";
import type { FormModalProps } from "../types";

export default function FormModal<TModel extends {}>({
	children,
	onSubmit,
	onCancel,
	okLoading,
	initialValues,
	...config
}: FormModalProps<TModel>) {
	const [form] = Form.useForm<TModel>();
	const onFinish = (values: TModel) => {
		onSubmit?.(values);
	};
	const onKeyDown = (e: KeyboardEvent) => {
		if (e.key === "Enter") {
			form.submit();
		}
	};

	const handleOk = () => {
		form.submit();
	};

	const { close } = useModalRef();
	const handleCancel = () => {
		close();
		onCancel?.();
	};

	return (
		<ModalContent>
			<Form
				form={form}
				initialValues={initialValues}
				autoComplete="off"
				onSubmit={onFinish}
				onKeyDown={onKeyDown}
			>
				<ModalBody>{children}</ModalBody>
				<ModalFooter
					okText={config.okText}
					cancelText={config.cancelText}
					okLoading={okLoading}
					onOk={handleOk}
					onCancel={handleCancel}
				/>
			</Form>
		</ModalContent>
	);
}
